#include <vector>
#include <stack>
using namespace std;


 struct TreeNode 
 {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
 
class Solution {
public:

    //二叉树的非递归前序遍历
    vector<int> preorderTraversal(TreeNode* root) 
    {
        vector<int>res;
        stack<TreeNode*>st;
        TreeNode* cur=root;
        while(cur!=nullptr || !st.empty())
        {
            while(cur)
            {
                res.push_back(cur->val);
                st.push(cur);
                cur=cur->left;
            }
            //左树全遍历完了 此时cur是空
            //现在需要把栈顶结点的右子树入栈
            cur=st.top()->right;
            st.pop();
        }
        return res;
    }

    vector<int> inorderTraversal(TreeNode* root)
    {
        vector<int>res;
        stack<TreeNode*>st;
        TreeNode* cur=root;
        while(cur || !st.empty())
        {
            //把cur的左树全部入栈 由于是中序遍历 不在这里面push_back
            while(cur)
            {
                st.push(cur);
                cur=cur->left;
            }
            //cur现在是空 现在需要打印 cur的父节点的值 并让栈顶结点的右树进行入栈
            cur=st.top()->right;
            res.push_back(st.top()->val);
            st.pop();
        }
        return res;
    }

    vector<int> postorderTraversal(TreeNode* root) 
    {
        vector<int>res;
        stack<TreeNode*> st;
        TreeNode* cur=root;
        TreeNode* prev=nullptr;
        while(cur || !st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur=cur->left;
            }
            TreeNode* top=st.top();

            if(top->right==nullptr)
            {
                //这个结点的左右孩子都是空
                res.push_back(top->val);
                prev=top;//记录遍历的结点
                st.pop();
            }
            else if(top->right==prev)
            {
                //这个结点的右孩子 就是上一次push_back的
                //证明他的右树也已经遍历完毕
                res.push_back(top->val);
                prev=top;
                st.pop();
            }
            else
            {
                //这个节点要想push_back 先需要让他的右树遍历完毕
                cur=top->right;
            }

        }
        return res;
    }

    //层序遍历
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        vector<vector<int>>res;
        queue<TreeNode*> q;
        if(root!=nullptr) q.push(root);
        while(!q.empty())
        {
            int size=q.size();
            vector<int>tmp;
            while(size--)
            {
                TreeNode* front=q.front();
                q.pop();
                tmp.push_back(front->val);
                if(front->left) q.push(front->left);
                if(front->right)q.push(front->right);
            }
            res.push_back(tmp);
        }
        return res;
    }
};